<?php

/**
 * Class BrainStorm.php
 *
 * Class that deals with the storage/management of questions inserted by users
 * in the brainstorm stage
 *
 * @author Jose Oliveira <jafo@ua.pt> 2012
 */


class BrainStorm{

	private $questionID;
	private $question;
	Private $projectID;
	private $userID;
	private $dateHour;
	private $edited;

	/**
	 * 
	 * @param string $question
	 * @param integer $projectID
	 * @param integer $userID
	 */
	function __construct($question, $projectID, $userID){

		if(isset($question) && isset($projectID) && isset($userID)){
			$this->question=$question;
			$this->projectID=$projectID;
			$this->userID=$userID;
		}
	}

	/**
	 * Method that stores an question on the table BrainStorm case this is 
	 * not an edtition to a previously made question​​.
	 * return 0: storing of the question has failed
	 * return 1: improved question stored with success
	 * return 2: the question has been previously entered by the user
	 * @throws Exception
	 * @return integer
	 */
	public function addQuestion(){

		if($this->validQuestion($this->question, $this->userID, $this->projectID)){
			$date=date("Y-m-d H:i:s");

			$conn=new ConnDBUser();
			$conn->connect();    //liga à base de dados com privilégios de utilizador web

			$question=mysql_real_escape_string($this->question);
			$result=mysql_query("insert into brainStorm(question, edited, dateHour, projectID, userID, state)
			values('$question', 0, '" . $date . "', '" . $this->projectID . "', '" . $this->userID . "', 1)");

			if(!$result){
				throw new Exception("Lamentamos mas ocorreu um erro");
			}

			try{
				$conn->disconnect($result);
				return 1;
			}catch(Exception $e){
				$e->getMessage();
			}

		}else{
			return 2;
		}
	}

	/**
	 * Method that returns the info about all questions of a user that haven't been edited
	 * @param integer $projectID
	 * @param integer $userID
	 * @return array
	 */
	public function getAllQuestionOfUser($projectID, $userID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select questionID from brainStorm where edited='0' and projectID='$projectID' and userID='$userID' and state='1'");

		if($result){
			$questArr=array();

			while($registo=mysql_fetch_array($result)){
				array_push($questArr, $registo['questionID']);
			}
			$conn->disconnect($result);
			return $questArr;
		}else{
			$conn->disconnect();
			echo"Lamentamos mas ocorreu um erro: " . mysql_error();
			return '';
		}
	}

	/**
	 * Method that returns the info about all questions of a project that haven't been edited
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function getAllQuestions($projectID){

		$conn = new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select * from brainStorm where projectID=$projectID and edited=0 and state=1 order by userID asc");  //query que obtem todas as questões que não foram editadas inerentes a um dado projeto

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ao obter as questões");
		}

		try{
			$quest=array();
			while($registo=mysql_fetch_array($result)){
				array_push($quest, $registo);
			}
				
			$conn->disconnect($result);
			return $quest;
				
		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method that checks if a question was edited
	 * @param integer $questionID
	 * @return bool
	 */
	public function isEdited($questionID){
		
		$conn=new ConnDBUser();
		$conn->connect();

		$sql="select edited from brainStorm where questionID='$questionID'";
		$result=mysql_query($sql);

		if($result){
			$registo=mysql_fetch_array($result);
			$conn->disconnect();

			if($registo['edited'] == 1){
				return true;
			}else{
				return false;
			}

		}else{
			$conn->disconnect();
			echo "Lamentamos mas ocorreu um erro: " . mysql_error();
			return '';
		}
	}
	
	/**
	 * Method that deletes all questions of a project
	 * @param integer $projectID
	 */
	public function cleanProjectQuestions($projectID){
		
		$conn=new ConnDBUser();
		$conn->connect();

		$sql="delete from brainStorm where projectID='$projectID'";
		$result=mysql_query($sql);

		if($result){
			$conn->disconnect();
			return true;
		}else{
			$conn->disconnect();
			echo "Lamentamos mas ocorreu um erro: " . mysql_error();
			return false;
		}
	}

	/**
	 * Method that verifies if this question has not yet been entered by this user 
	 * @param string $question
	 * @param integer $userID
	 * @param integer $projectID
	 * @throws Exception
	 * @return bool
	 */
	private function validQuestion($question, $userID, $projectID){
		/*
		 * Método que verifica se o utilizador não insere 2 vezes a mesma questão;
		 * Se tentar faze-lo, o sistema deve impedir que isso aconteça, para que em fases posteriores consiga
		 * fazer uma correcta filtragem dos dados;
		 * Se a questão que o utilizador tentar inserir for válida, o método retorna true; caso contrário, retorna false;
		 */

		$conn=new ConnDBUser();
		$conn->connect();

		$question=mysql_real_escape_string($question);
		$result=mysql_query("select * from brainStorm where question='$question' and projectID='$projectID' and userID='$userID' and state='1'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);
			$conn->disconnect($result);
			if($num==0){
				//significa que este grupo nunca inseriu uma questão igual a esta neste projecto e podemos retornar true;
				return true;
			}else{
				return false;
			}
		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method that update de field "edited" of this question to "1"
	 * @param integer $questionID
	 * @throws Exception
	 * @return bool
	 */
	public function updateToEdited($questionID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("update brainStorm set edited=1 where questionID=$questionID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro: " . mysql_error());
		}

		try{
			$conn->disconnect($result);
			return true;
		}catch (Exception $e){
			$e->getMessage();
		}

		$conn->disconnect($result);
		return false;
	}

 	/**
 	 * Method that returns the IDs of all questions that have been edited
	 * from a certain user. 
	 * Note: when we print the questions of the user, we should only print the
	 * latest update of each question
 	 * @param integer $projectID
 	 * @param integer $userID
 	 * @throws Exception
 	 * @return array
 	 */
	public function editedQuestionsIDs($projectID, $userID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select questionID from brainStorm where edited=1 and projectID=$projectID and userID=$userID and state='1'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);

			if($num==0){
				$conn->disconnect($result);
				return 0;           //se não houverem questões editadas, não retornamos nada
			}else{
				$ids=array();

				while($registo=mysql_fetch_array($result)){
					$temp=$registo['questionID'];       //criação de array uni-dimensional com os ID's das questões que sofreram edição
					array_push($ids, $temp);
				}

				$conn->disconnect($result);
				return $ids;
			}
		}catch(Exception $e){
			echo $e->getMessage();
		}

		$conn->disconnect($result);
		return 0;
	}

	/**
	 * Method that returns the IDs of all questions that have been edited in a project
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function allEditedIDs($projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select questionID from brainStorm where edited=1 and projectID=$projectID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);

			if($num==0){
				$conn->disconnect($result);
				return 0;           //se não houverem questões editadas, não retornamos nada
			}else{
				$ids=array();

				while($registo=mysql_fetch_array($result)){
					$temp=$registo['questionID'];       //criação de array uni-dimensional com os ID's das questões que sofreram edição
					array_push($ids, $temp);
				}

				$conn->disconnect($result);
				return $ids;
			}
		}catch(Exception $e){
			echo $e->getMessage();
		}

	}

	/**
	 * Method that returns the info about all questions of a user that haven't been edited
	 * @param integer $userID
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function getNoEditedQuestionInfo($userID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select questionID, question, dateHour, projectID, userID from brainStorm where userID=$userID and projectID=$projectID and edited=0 and state='1'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{

			$num=mysql_num_rows($result);

			if($num>0){
				$info=array();
				while($registo=mysql_fetch_array($result)){
					array_push($info, $registo);
				}
				
				$conn->disconnect($result);
				return $info;
			}else{
				$conn->disconnect($result);
				return '';
			}
			
		}catch(Exception $e){
			echo $e->getMessage();
		}
	}

	/**
	 * Method used to unset a certain question. Used when a user wants to delete a question
	 * @param integer $questionID
	 * @throws Exception
	 * @return bool
	 */
	public function unsetQuestion($questionID){
		
		$conn=new ConnDBUser();
		$conn->Connect();

		$result=mysql_query("update brainStorm set state='0' where questionID=$questionID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ao eliminar a questão");
		}

		try{
			$conn->disconnect($result);
			return true;
		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Returns the number of active questions (not deleted by users) inserted by a certain user, 
	 * in a certain project, in the brainstorm stage
	 * @param integer $userID
	 * @param integer $projectID
	 * @throws Exception
	 * @return integer
	 */
	public function getNumberOfQuestions($userID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select questionID from brainStorm where projectID='$projectID' and userID='$userID' and state='1'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{
			$num=mysql_num_rows($result);
			$conn->disconnect($result);
			return $num;

		}catch(Exception $e){
			$e->getMessage();
		}
	}

	/**
	 * Method that returns an array with info properly formatted for the project administrator, with questions, 
	 * edited and unedited from each user in a certain project
	 * @param integer $userID
	 * @param integer $projectID
	 * @throws Exception
	 * @return array
	 */
	public function preparedArrayForAdmin($userID, $projectID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select * from brainStorm where userID=$userID and projectID=$projectID");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro ao obter as questões do grupo");
		}

		try{

			$firstArray=array();
			while($registo=mysql_fetch_array($result)){
				array_push($firstArray, $registo);
			}

			$conn->disconnect($result);

			//agora que já temos um array com todas as funções, vamos passá-lo por um método privado, que trata da verificação da existencia de edições
			$arrayFinal=$this->tuneAdminArray($firstArray);
			return $arrayFinal;

		}catch(Exception $e){
			$e->getMessage();
		}

	}

	/**
	 * Method that completes the array of the method preparedArrayForAdmin
	 * @param array $array
	 * @return array
	 */
	private function tuneAdminArray($array){
		/*
		 *
		 * Método privado que acrescenta ao array das perguntas dos grupos as respetivas edições
		 */

		$cleanArray=array();

		for($i=0; $i<count($array); $i++){

			if($array[$i]['edited']==1){

				//se for editado, vamos  buscar todas as versões:
				$edBrainStorm=new EditedBrainStorm('', '');
				$tempArray=$edBrainStorm->showPreviousVersionsOfQuestion($array[$i]['questionID']);
				unset($edImpQuest);
				$cleanArray=array_merge($cleanArray, $tempArray);
			}else{
				$tempArray=array("question" => $array[$i]['question'], "dateHour" => $array[$i]['dateHour'], "state" => $array[$i]['state'], "userID" => $array[$i]['userID'], "edited" => 0, "instance" => 0, "bold" => 1, "origQuestID" => $array[$i]['questionID']);
				array_push($cleanArray, $tempArray);
			}

		}

		return $cleanArray;
	}

}
?>